<template>
  <div class="register-container">
    <el-form :model="{ email, username, password }" :rules="rules" ref="formRef" @submit.prevent="submitForm">
      <h1 align="center">个人网盘注册</h1>
      <el-form-item label="Email" prop="email">
        <el-input v-model="email" placeholder="Enter your email" autocomplete="email"></el-input>
      </el-form-item>
      <el-form-item label="Password" prop="password">
        <el-input v-model="password" type="password" placeholder="Enter your password" autocomplete="current-password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">Register</el-button>
        <el-button type="text" @click="goToLogin">Login</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'Register',
  setup() {
    const router = useRouter()
    const email = ref('')
    const username = ref('')
    const password = ref('')
    const formRef = ref(null)

    const rules = {
      email: [
        { required: true, message: 'Email is required', trigger: 'blur' },
        { type: 'email', message: 'Please enter a valid email', trigger: 'blur' }
      ],
      password: [
        { required: true, message: 'Password is required', trigger: 'blur' },
        { min: 4, max: 12, message: 'Password length should be between 4 and 12', trigger: 'blur' }
      ]
    }

    const submitForm = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post('/register', {
              email: email.value,
              username: username.value,
              password: password.value
            })
            if (response.data.success) {
              ElMessage.success('Registration successful')
              await router.push('/login')
            } else {
              ElMessage.error(response.data.message)
            }
          } catch (error) {
            ElMessage.error('An error occurred during registration')
          }
        } else {
          ElMessage.error('Please check the form fields')
        }
      })
    }

    const goToLogin = () => {
      router.push('/login')
    }

    return {
      email,
      username,
      password,
      formRef,
      rules,
      submitForm,
      goToLogin
    }
  }
}
</script>
<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.el-form {
  width: 300px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>
